package db

import (
	"fmt"
	"gitee.com/dehow/k8sdev/conf"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

func isInDocker() bool {
	fileInfo, err := os.Stat("/.dockerenv")
	if err != nil {
		return false
	}
	return !fileInfo.IsDir()
}

func connectDbOrder() *gorm.DB {
	cf := conf.GetProjectDbConf()
	if isInDocker() {
		cf.Host = os.Getenv("MYSQL_HOST")
		cf.Username = os.Getenv("MYSQL_ROOT_USERNAME")
		cf.Password = os.Getenv("MYSQL_ROOT_PASSWORD")
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cf.Username, cf.Password, cf.Host, cf.Port, cf.DbName)
	db, err := gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic("数据库连接错误:" + err.Error())
	}
	sqlDB, _ := db.DB()
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(2)
	// SetMaxOpenConns 设置打开数据库连接的最大数量。
	sqlDB.SetMaxOpenConns(10)
	return db
}

var dbOrder *gorm.DB

func init() {
	dbOrder = connectDbOrder()
}

func GetDbOrder() *gorm.DB {
	if dbOrder == nil {
		dbOrder = connectDbOrder()
		if dbOrder == nil {
			panic("无数据库连接")
		}
	}
	return dbOrder
}
